﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IdentityModel.Tokens.Jwt;//引用jwt
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.Data;
using System.Data.SqlClient;
using Dapper;
namespace TestFunction
{
    /// <summary>
    /// 本类用来写测试功能
    /// </summary>
    internal class Program
    {
        /// <summary>
        ///  测试生成token
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            TestDapper();

            // 创建Token测试
            // CreateToken();
            //测试生成SKU程序
            //List<string> str1 = new List<string> 
            //{
            //    "白","黄","红","蓝"
            //};
            //List<string> str2 = new List<string>
            //{
            //    "37","38","39","40"
            //};
            //List<string> str3 = new List<string>
            //{
            //    "少女版","成人版","老人版"
            //};
            ////////生成sku 4*4*3=48//////////////
            ///////一种版式

            ///////两种版式
            //for (int i = 0; i < str1.Count; i++)
            //{
            //    for (int j = 0; j < str2.Count; j++)
            //    {
            //        Console.WriteLine(str1[i] + " " + str2[j]);
            //    }
            //}
            //Console.WriteLine("===================================");
            ///////三种版式
            //for (int i = 0; i < str1.Count; i++)
            //{
            //    for (int j = 0; j < str2.Count; j++)
            //    {
            //        for (int k = 0; k < str3.Count; k++)
            //        {
            //            Console.WriteLine(str1[i] + " " + str2[j]+" " + str3[k]);
            //        }

            //    }                                                                
            //}
            ////四种版式
            ////五种版式
            ////n种版式
            //Console.WriteLine("=================================================");
            //List<string> L1 = new List<string>() { "蓝色", "灰色", "红色" };
            //List<string> L2 = new List<string>() { "S", "M", "L" };
            //List<string> L3 = new List<string>() { "圆领", "心领" };

            //List<List<string>> ooop = new List< List<string> >() { L1, L2, L3 };


            //if (ooop.Count > 0)
            //{
            //    DHG("", 0, ooop[0], ooop);
            //}
            ////////////////////////////////

            //List<string> L1 = new List<string>() { "蓝色", "灰色", "红色" };
            //List<string> L2 = new List<string>() { "S", "M", "L" };
            //List<string> L3 = new List<string>() { "圆领", "心领" };

            //List<List<string>> ooop = new List<List<string>>() { L1, L2, L3 };


            //List<string> reAttrList = new List<string >();

            //if (ooop.Count > 0)
            //{
            //    DHG2("", 0, ooop[0], ooop, ref reAttrList);
            //}

            //foreach (var str in reAttrList)
            //{
            //    Console.WriteLine(str);
            //}

            Console.ReadLine();
        }
        /// <summary>
        /// SKU生成，递归算法
        /// </summary>
        public static void CreateSKU()
        {

        }

        public static void CreateToken()
        {
            //引用System.IdentityModel.Tokens.Jwt
            DateTime utcNow = DateTime.UtcNow;
            string key = "f47b558d-7654-458c-99f2-13b190ef0199";
            SecurityKey securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key));

            var claims = new List<Claim>() {
                new Claim("ID","1"),
                new Claim("Name","fan")
            };
            JwtSecurityToken jwtToken = new JwtSecurityToken(
                issuer: "fan",
                audience: "audi~~!",
                claims: claims,
                notBefore: utcNow,
                expires: utcNow.AddYears(1),
                signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
                );

            //生成token方式1
            string token1 = new JwtSecurityTokenHandler().WriteToken(jwtToken);
            //输出字符串
            Console.WriteLine("方法一生成：" + token1);

            var tokenDescriptor = new SecurityTokenDescriptor // 创建一个 Token 的原始对象
            {
                Issuer = "fan",
                Audience = "audi",
                Subject = new ClaimsIdentity(new[]
                       {
                            new Claim(ClaimTypes.Name, "")
                        }),
                Expires = DateTime.Now.AddMinutes(60),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key)), SecurityAlgorithms.HmacSha256)
            };
            //生成token方式2
            SecurityToken securityToken = new JwtSecurityTokenHandler().CreateToken(tokenDescriptor);
            var token2 = new JwtSecurityTokenHandler().WriteToken(securityToken);
            Console.WriteLine("方法二生成：" + token2);
            //////////////////////////////////////////////////////
            //校验token
            var validateParameter = new TokenValidationParameters()
            {
                ValidateLifetime = true,
                ValidateAudience = true,
                ValidateIssuer = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = "fan",
                ValidAudience = "audi~~!",
                IssuerSigningKey = securityKey,
            };
            //不校验，直接解析token
            //jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(token1);
            try
            {
                //校验并解析token
                var claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(token1, validateParameter, out SecurityToken validatedToken);//validatedToken:解密后的对象
                var jwtPayload = ((JwtSecurityToken)validatedToken).Payload.SerializeToJson(); //获取payload中的数据 

                Console.WriteLine("效验出来的数据：" + jwtPayload);

            }
            catch (SecurityTokenExpiredException)
            {
                //表示过期
            }
            catch (SecurityTokenException)
            {
                //表示token错误
            }
            ///////////验证方法////////////////////

            ///////////////////////////////////////
        }

        //生成SKU
        static void DHG(string nn, int c, List<string> L, List<List<string>> ooop)
        {
            c = c + 1;
            foreach (var value in L)
            {
                if (ooop.Count > c)
                {
                    var mm = nn + value;
                    DHG(mm, c, ooop[c], ooop); //这里用了递归？什么是递归？方法中调用方法本身，必须有一个退出功能
                }
                else
                {
                    Console.WriteLine(nn + value);
                }
            }
        }
        ///
        static void DHG2(string nn, int c, List<string> L,
            List<List<string>> ooop, ref List<string> reAttrList)
        {
            c = c + 1;
            foreach (var value in L)
            {
                if (ooop.Count > c)
                {
                    var mm = nn + value + ",";

                    DHG2(mm, c, ooop[c], ooop, ref reAttrList); //这里用了递归？什么是递归？方法中调用方法本身，必须有一个退出功能
                }
                else
                {
                    //Console.WriteLine(nn + value);
                    reAttrList.Add(nn + value);
                }
            }
        }


        //Dapper使用方法
        public static void TestDapper()
        {
            //增加，角色表
            //1 使用Dapper步骤 http://www.manongjc.com/detail/52-getkdflxpshupac.html
            // 连接字符串
            //增加过程
            string connectionString = "Data Source=WIN-OIDNG5LD1UR;Initial Catalog=MyShoppingDB_Vue;User ID=sa;pwd=accp1234";
            IDbConnection dbConnection = new SqlConnection(connectionString);
            //sql增加语句
            string addSql = "insert into [sp_role](role_name, ps_ids, ps_ca, role_desc) " +
                "values(@role_name, @ps_ids, @ps_ca, @role_desc)";
            //要增加的对象
            Models.sp_role roleobj = new Models.sp_role
            {
                role_name = "测试角色ID",
                ps_ca = "Goods-index,Goods-tianjia",
                ps_ids = "101,103,104",
                role_desc = ""
            };
            //调用Dapper中方法
            int n = dbConnection.Execute(addSql, roleobj);
            Console.WriteLine("增加成功" + n);
            //增加多个对象
            //批量插入数据
            List<Models.sp_role> rolelist = new List<Models.sp_role>()
            {
              new Models.sp_role() {
                role_name = "批量角色1",
                        ps_ca = "Goods-index,Goods-tianjia",
                        ps_ids = "101,103,104",
                        role_desc = ""
              },
              new Models.sp_role() {  role_name = "批量角色2",
                        ps_ca = "Goods-index,Goods-tianjia",
                        ps_ids = "101,103,104",
                        role_desc = "" },
              new Models.sp_role() {  role_name = "批量角色3",
                        ps_ca = "Goods-index,Goods-tianjia",
                        ps_ids = "101,103,104",
                        role_desc = ""}
            };
            //调用方法
           int n2=  dbConnection.Execute(addSql, rolelist);
            Console.WriteLine("批量增加："+n2);
            //

        }

    }

    /// <summary>
    /// SKU参数类
    /// </summary>
    public class Attr
    {
        public int arrId { get; set; }
        public string arrName { get; set; }

        public string arrVal { get; set; }
    }
}
